<?php
/**
 * @description:
 * @author     : Geomen
 * @time       : 2019/1/24 10:38
 */


namespace App\Http\Controllers;


use App\Http\Resources\Permissions;
use App\Http\Resources\Roles;
use App\Http\Resources\UserCollection;
use App\Models\User;
use App\Repositories\UserRepository;
use Illuminate\Http\Request;
use Spatie\Permission\Exceptions\RoleAlreadyExists;
use Spatie\Permission\Exceptions\RoleDoesNotExist;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class UserController extends Controller
{
    /** @var UserRepository 注入的UserRepository */
    protected $userRepository;

    /**
     * UserController constructor.
     *
     * @param UserRepository $userRepository
     */
    public function __construct(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }

    /**
     * 列表
     *
     * @param Request $request
     *
     * @return UserCollection|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        if ($request->isMethod('post')) {
            $list = $this->userRepository->list();
            return new UserCollection($list);
        }
        return view('user.index');
    }

    /**
     * 添加管理员
     * @param Request $request
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function add(Request $request)
    {
        if ($request->isMethod('post')){
            $username = e($request->input('username'));
            $nickname = e($request->input('nickname'));
            $password = e($request->input('password'));
            $obj = User::query()->firstOrCreate(compact('username'));
            if (!$obj->wasRecentlyCreated){
                return redirect()->back()->withInput()->with('fail','登录账号已经存在');
            }
            $obj->nickname = $nickname;
            $obj->password = bcrypt($password);
            $obj->save();
            return redirect()->back()->with('success', '添加成功');
        }
        return view('user.add');
    }

    /**
     * 管理员状态设置
     *
     * @param Request $request
     *
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function setIsDel(Request $request)
    {
        $id = intval($request->input('id'));
        $is_del = abs($request->input('is_del') - 1);
        $info = User::query()->findOrFail($id);
        $info->is_del = $is_del;
        $info->save();
        $msg = $is_del == 0 ? '启用成功': '禁用成功';
        return response(['state' => self::SUCCESS,'message' => $msg]);
    }

    /**
     * 修改管理员信息
     *
     * @param Request $request
     * @param         $id
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit(Request $request, $id)
    {
        $info = User::query()->findOrFail($id);
        if ($request->isMethod('post')){
            $info->nickname = e($request->input('nickname'));
            $role = e($request->input('role'));
            if (filled($request->input('password'))){
                $info->password = bcrypt($request->input('password'));
            }
            if ($info->isDirty()){
                $info->save();
            }
            if (filled($role)){
                $roleArr = explode(',',$role);
                $info->assignRole($roleArr);
            }
            return $this->responseSuccess('管理员修改成功');
        }
        return view('user.edit',compact('info'));
    }

    /**
     * 行为列表
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function permission()
    {
        $list = Permission::query()->latest()->paginate();
        return view('user.permission',compact('list'));
    }

    /**
     * 添加行为
     *
     * @param Request $request
     *
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function addPermission(Request $request)
    {
        $name = e($request->input('name'));
        $action = e($request->input('action'));
        if (Permission::query()->where('name',$name)->exists()){
            return $this->responseFail('行为名称已经存在');
        }
        if (Permission::query()->where('action',$action)->exists()){
            return $this->responseFail('行为地址已经存在');
        }
        $obj = new Permission();
        $obj->fill(compact('name','action'));
        $obj->save();
        return $this->responseSuccess('行为添加成功');
    }

    /**
     * 角色列表
     */
    public function role()
    {
        $list = Role::query()->latest()->with('permissions')->paginate();
        return view('user.role',compact('list'));
    }

    /**
     * 添加角色
     *
     * @param Request $request
     *
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function addRole(Request $request)
    {
        $name = e($request->input('name'));
        try {
            $result = Role::create(compact('name'));
        }catch (RoleAlreadyExists $e){
            return $this->responseFail('角色名称已经存在');
        }
        return $this->responseSuccess('角色添加成功',$result);
    }

    /**
     * 分配行为
     *
     * @param Request $request
     * @param int     $id
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function editRole(Request $request, int $id)
    {
        try {
            $info = Role::findById($id);
        }catch (RoleDoesNotExist $e){
            return redirect('role')->with('fail','角色不存在');
        }
        if ($request->isMethod('post')){
            $name = e($request->input('name'));
            $permission = e($request->input('permission'));
            if (Role::query()->where('name',$name)->where('id','<>',$id)->exists()){
                return $this->responseFail('角色名称已经存在');
            }
            $info->name = $name;
            if ($info->isDirty('name')){
                $info->save();
            }
            if (filled($permission)){
                $permissionArr = explode(',',$permission);
                $isGod = array_first($permissionArr,function ($value,$key){
                    return $value == 0;
                },-1);
                $permissionArr = $isGod == 0 ? [0] : $permissionArr;
                $info->syncPermissions($permissionArr);
            }
            return $this->responseSuccess('行为分配成功');
        }
        return view('user.editRole',compact('info'));
    }

    /**
     * 获取所有行为
     *
     * @param Request $request
     *
     * @return Permissions
     */
    public function getAllPermission(Request $request)
    {
        if ($request->has('role_id')){
            $role = Role::findById($request->input('role_id'));
            return response(['state' => 'success','data' => $role->permissions]);
        }
        return new Permissions(Permission::all());
    }

    /**
     * 获取所有角色
     *
     * @param Request $request
     *
     * @return Roles|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     */
    public function getAllRole(Request $request)
    {
        if ($request->has('user_id')){
            $user = User::query()->findOrFail($request->input('user_id'));
            return response(['state' => 'success', 'data' => $user->roles]);
        }
        return new Roles(Role::all());
    }
}